import storageDict from './storageDict.js'

export const setUserInfo = function(obj) {
	if (typeof obj != "object") return false;
	uni.setStorageSync(storageDict.USER_INFO, JSON.stringify(obj))
}

export const getUserInfo = function() {
	let value = uni.getStorageSync(storageDict.USER_INFO)
	if (value) {
		return JSON.parse(value)
	} else {
		return {}
	}
}

export const getUrlparams = function(key) {
	let url = location.href.split('#')[0]
	try {
		let str1 = url.split('?')[1]
		let arr1 = str1.split('&')
		let obj = {}
		arr1.forEach((e, i) => {
			let str2 = e.split('=')
			obj[str2[0]] = str2[1]
		})
		if (obj[key]) {
			return obj[key]
		} else {
			return ''
		}
	} catch (e) {
		//TODO handle the exception
		return ''
	}
}

function filterArray(data, ParentNo) {
	let vm = this;
	var tree = [];
	var temp;
	for (var i = 0; i < data.length; i++) {
		if (data[i].ParentNo == ParentNo) {
			var obj = data[i];
			temp = filterArray(data, data[i].No);
			if (temp.length > 0) {
				obj.children = temp;
			}
			tree.push(obj);
		}
	}
	return tree;
}
export function buildTree(data, ParentNo) {
	return filterArray(data, ParentNo);
}

function findNode(arr, No, r) {
	for (let i = 0; i < arr.length; i++) {
		if (arr[i].No == No) {
			r.push({
				index: i,
				Name: arr[i].Name
			});
			return true;
		}
		if (arr[i].children) {
			let result = findNode(arr[i].children, No, r);
			if (result) {
				r.push({
					index: i,
					Name: arr[i].Name
				});
				return true;
			}
		}
	}
}
export function findIndex(arr, No) {
	let path = [];
	findNode(arr, No, path);
	return path.reverse();
}


function findNode2(arr, value, r) {
	for (let i = 0; i < arr.length; i++) {
		if (arr[i].value == value) {
			r.push({
				index: i,
				Name: arr[i].label
			});
			return true;
		}
		if (arr[i].children) {
			let result = findNode2(arr[i].children, value, r);
			if (result) {
				r.push({
					index: i,
					Name: arr[i].label
				});
				return true;
			}
		}
	}
}
export function findIndex2(arr, value) {
	let path = [];
	findNode2(arr, value, path);
	return path.reverse();
}


export function formatDate(date, fmt) {
	var o = {
		"M+": date.getMonth() + 1, //月份
		"d+": date.getDate(), //日
		"h+": date.getHours(), //小时
		"m+": date.getMinutes(), //分
		"s+": date.getSeconds(), //秒
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度
		S: date.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(
			RegExp.$1,
			(date.getFullYear() + "").substr(4 - RegExp.$1.length)
		);
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(
				RegExp.$1,
				RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
			);
	return fmt;
}

export const formDataString = function(obj) {
	let result = ''
	for (let name of Object.keys(obj)) {
		let value = obj[name];
		result +=
			'\r\n--XXX' +
			'\r\nContent-Disposition: form-data; name=\"' + name + '\"' +
			'\r\n' +
			'\r\n' + value
	}
	return result + '\r\n--XXX--'
}
